<template>
	<view class="container">
		<view class="header">
			<text class="title">添加闹钟</text>
		</view>
		
		<view class="form-item">
			<text class="label">时间</text>
			<picker mode="time" :value="formatTime(alarm.hour, alarm.minutes)" @change="timeChange">
				<view class="picker-value">
					{{formatTime(alarm.hour, alarm.minutes)}}
				</view>
			</picker>
		</view>
		
		<view class="form-item">
			<text class="label">名称</text>
			<input type="text" v-model="alarm.name" placeholder="请输入闹钟名称" class="input" />
		</view>
		
		<view class="form-item">
			<text class="label">重复</text>
			<view class="weekday-selector">
				<view 
					v-for="(day, index) in weekdays" 
					:key="index"
					:class="['weekday-item', isWeekdaySelected(day.value) ? 'selected' : '']"
					@click="toggleWeekday(day.value)"
				>
					{{day.label}}
				</view>
			</view>
		</view>
		
		<view class="form-item custom-cycle-toggle">
			<text class="label">自定义周期</text>
			<view class="custom-cycle-info">
				<text class="custom-cycle-desc">系统闹钟不支持自定义周期，应用将通过内部逻辑实现此功能</text>
			</view>
			<switch :checked="showCustomCycle" @change="toggleCustomCycle" color="#007AFF" />
		</view>
		
		<view class="form-item" v-if="showCustomCycle">
			<text class="label">自定义周期</text>
			<view class="custom-cycle">
				<view class="cycle-item">
					<text class="cycle-label">第一周</text>
					<view class="weekday-selector">
						<view 
							v-for="(day, index) in weekdays" 
							:key="index"
							:class="['weekday-item', isWeekdayInCycle(0, day.value) ? 'selected' : '']"
							@click="toggleWeekdayInCycle(0, day.value)"
						>
							{{day.label}}
						</view>
					</view>
				</view>
				<view class="cycle-item">
					<text class="cycle-label">第二周</text>
					<view class="weekday-selector">
						<view 
							v-for="(day, index) in weekdays" 
							:key="index"
							:class="['weekday-item', isWeekdayInCycle(1, day.value) ? 'selected' : '']"
							@click="toggleWeekdayInCycle(1, day.value)"
						>
							{{day.label}}
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="form-item">
			<text class="label">铃声</text>
			<picker @change="ringtoneChange" :value="ringtoneIndex" :range="ringtones" range-key="name">
				<view class="picker-value">
					{{ringtones[ringtoneIndex].name}}
				</view>
			</picker>
		</view>
		
		<view class="form-item">
			<switch :checked="alarm.enabled" @change="toggleEnabled" color="#007AFF" />
			<text class="switch-label">启用闹钟</text>
		</view>
		
		<view class="btn-group">
			<button class="btn cancel" @click="cancel">取消</button>
			<button class="btn save" @click="saveAlarm">保存</button>
		</view>
	</view>
</template>

<script>
	import { alarmAdd } from "@/uni_modules/laoqianjunzi-alarm";
import { loadAlarmList, saveAlarmList, formatTime, formatWeekday, switchToNextCycle } from "@/utils/alarm-utils";
	
	export default {
		data() {
			return {
				alarm: {
					name: '闹钟',
					hour: 8,
					minutes: 0,
					weekday: '',
					ringtone: 'https://jubaomusics.oss-cn-beijing.aliyuncs.com/%E4%B8%89%E5%8F%AA%E5%B0%8F%E7%8C%AA/%E4%B8%89%E5%8F%AA%E5%B0%8F%E7%8C%AA.mp3',
					enabled: true,
					customCycle: false,
					cycles: [
						'', // 第一周的重复日
						''  // 第二周的重复日
					],
					currentCycleIndex: 0 // 当前处于哪个周期 (0 或 1)
				},
				weekdays: [
					{ label: '一', value: '1' },
					{ label: '二', value: '2' },
					{ label: '三', value: '3' },
					{ label: '四', value: '4' },
					{ label: '五', value: '5' },
					{ label: '六', value: '6' },
					{ label: '日', value: '7' }
				],
				ringtones: [
					{ name: '小猪', value: 'https://jubaomusics.oss-cn-beijing.aliyuncs.com/%E4%B8%89%E5%8F%AA%E5%B0%8F%E7%8C%AA/%E4%B8%89%E5%8F%AA%E5%B0%8F%E7%8C%AA.mp3' },
					{ name: '默认', value: 'content://settings/system/alarm_alert' },
					{ name: '无声', value: '' }
				],
				ringtoneIndex: 0,
				showCustomCycle: false,
				editMode: false,
				editIndex: -1
			};
		},
		onLoad(options) {
			// 如果是编辑模式，加载闹钟数据
			if (options.index !== undefined) {
				this.editMode = true;
				this.editIndex = parseInt(options.index);
				this.loadAlarmData();
			}
		},
		methods: {
			// 加载闹钟数据（编辑模式）
			loadAlarmData() {
				try {
					const alarmList = loadAlarmList();
					if (alarmList[this.editIndex]) {
						this.alarm = {...alarmList[this.editIndex]};
						
						// 设置铃声索引
						const ringtoneIndex = this.ringtones.findIndex(item => item.value === this.alarm.ringtone);
						this.ringtoneIndex = ringtoneIndex >= 0 ? ringtoneIndex : 0;
						
						// 检查是否有自定义周期
						if (this.alarm.cycles && this.alarm.cycles.length === 2) {
							this.showCustomCycle = true;
						}
					}
				} catch (e) {
					console.error('加载闹钟数据失败', e);
				}
			},
			
			// 格式化时间显示
			formatTime(hour, minutes) {
				return formatTime(hour, minutes);
			},
			
			// 时间选择器变化
			timeChange(e) {
				const timeArr = e.detail.value.split(':');
				this.alarm.hour = parseInt(timeArr[0]);
				this.alarm.minutes = parseInt(timeArr[1]);
			},
			
			// 铃声选择器变化
			ringtoneChange(e) {
				this.ringtoneIndex = e.detail.value;
				this.alarm.ringtone = this.ringtones[this.ringtoneIndex].value;
			},
			
			// 切换启用状态
			toggleEnabled(e) {
				this.alarm.enabled = e.detail.value;
			},
			
			// 检查某天是否被选中
			isWeekdaySelected(day) {
				return this.alarm.weekday.includes(day);
			},
			
			// 切换某天的选中状态
			toggleWeekday(day) {
				if (this.showCustomCycle) {
					// 如果启用了自定义周期，则禁用普通重复选择
					return;
				}
				
				if (this.isWeekdaySelected(day)) {
					this.alarm.weekday = this.alarm.weekday.replace(day, '');
				} else {
					this.alarm.weekday += day;
					// 按照顺序排序
					this.alarm.weekday = this.alarm.weekday.split('').sort().join('');
				}
			},
			
			// 检查某天是否在特定周期中被选中
			isWeekdayInCycle(cycleIndex, day) {
				return this.alarm.cycles[cycleIndex].includes(day);
			},
			
			// 切换特定周期中某天的选中状态
			toggleWeekdayInCycle(cycleIndex, day) {
				if (this.isWeekdayInCycle(cycleIndex, day)) {
					this.alarm.cycles[cycleIndex] = this.alarm.cycles[cycleIndex].replace(day, '');
				} else {
					this.alarm.cycles[cycleIndex] += day;
					// 按照顺序排序
					this.alarm.cycles[cycleIndex] = this.alarm.cycles[cycleIndex].split('').sort().join('');
				}
				
				// 更新当前周期的weekday
				this.updateCurrentWeekday();
			},
			
			// 更新当前周期的weekday
			updateCurrentWeekday() {
				this.alarm.weekday = this.alarm.cycles[this.alarm.currentCycleIndex];
			},
			
			// 切换自定义周期显示
			toggleCustomCycle(e) {
				this.showCustomCycle = e.detail.value;
				
				if (this.showCustomCycle) {
					// 如果启用自定义周期，初始化周期数据
					if (!this.alarm.cycles) {
						this.alarm.cycles = ['', ''];
					}
					
					// 如果已有普通重复设置，将其复制到第一个周期
					if (this.alarm.weekday) {
						this.alarm.cycles[0] = this.alarm.weekday;
					}
					
					this.alarm.customCycle = true;
					this.alarm.currentCycleIndex = 0;
				} else {
					// 如果禁用自定义周期，使用普通重复设置
					this.alarm.customCycle = false;
					
					// 如果第一个周期有设置，将其复制到普通重复
					if (this.alarm.cycles && this.alarm.cycles[0]) {
						this.alarm.weekday = this.alarm.cycles[0];
					}
				}
			},
			
			// 取消
			cancel() {
				uni.navigateBack();
			},
			
			// 保存闹钟
			saveAlarm() {
				if (!this.alarm.name.trim()) {
					uni.showToast({
						title: '请输入闹钟名称',
						icon: 'none'
					});
					return;
				}
				
				// 如果是自定义周期，但两个周期都为空
				if (this.showCustomCycle && !this.alarm.cycles[0] && !this.alarm.cycles[1]) {
					uni.showToast({
						title: '请至少选择一天',
						icon: 'none'
					});
					return;
				}
				
				// 如果不是自定义周期，但没有选择重复日
				if (!this.showCustomCycle && !this.alarm.weekday) {
					// 如果没有选择重复日，默认为单次闹钟
					this.alarm.weekday = '';
				}
				
				try {
					// 获取现有闹钟列表
					let alarmList = loadAlarmList();
					
					// 创建要保存的闹钟对象
					const alarmToSave = {
						name: this.alarm.name,
						hour: this.alarm.hour,
						minutes: this.alarm.minutes,
						weekday: this.alarm.weekday,
						ringtone: this.alarm.ringtone,
						enabled: this.alarm.enabled,
						customCycle: this.showCustomCycle,
						cycles: this.showCustomCycle ? this.alarm.cycles : null,
						currentCycleIndex: this.showCustomCycle ? this.alarm.currentCycleIndex : 0
					};
					
					if (this.editMode) {
						// 编辑模式：更新现有闹钟
						alarmList[this.editIndex] = alarmToSave;
					} else {
						// 添加模式：添加新闹钟
						alarmList.push(alarmToSave);
					}
					
					// 保存到本地存储
					saveAlarmList(alarmList);
					
					// 如果闹钟已启用，设置系统闹钟
					if (alarmToSave.enabled) {
						this.setSystemAlarm(alarmToSave);
					}
					
					uni.showToast({
						title: this.editMode ? '闹钟已更新' : '闹钟已添加',
						icon: 'success'
					});
					
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
					
				} catch (e) {
					console.error('保存闹钟失败', e);
					uni.showToast({
						title: '保存闹钟失败',
						icon: 'none'
					});
				}
			},
			
			// 设置系统闹钟
			setSystemAlarm(alarm) {
				// 如果是自定义周期，使用当前周期的weekday
				const weekday = alarm.customCycle ? alarm.cycles[alarm.currentCycleIndex] : alarm.weekday;
				
				const params = {
					name: alarm.name,
					weekday: weekday,
					hour: alarm.hour,
					minutes: alarm.minutes,
					ringtone: alarm.ringtone
				};
				
				alarmAdd({
					params: params,
					success: (res) => {
						console.log('success', res);
						
						// 如果是自定义周期，设置定时器在闹钟触发后切换到下一个周期
						if (alarm.customCycle) {
							// 计算下一次闹钟触发的时间
							const now = new Date();
							const alarmTime = new Date();
							alarmTime.setHours(alarm.hour);
							alarmTime.setMinutes(alarm.minutes);
							alarmTime.setSeconds(0);
							
							// 如果闹钟时间已过，设置为明天
							if (alarmTime <= now) {
								alarmTime.setDate(alarmTime.getDate() + 1);
							}
							
							// 计算时间差（毫秒）
							const timeDiff = alarmTime.getTime() - now.getTime();
							
							// 设置定时器，在闹钟触发后切换周期
							setTimeout(() => {
								this.switchToNextCycle(alarm);
							}, timeDiff + 1000); // 加1秒确保闹钟已触发
						}
					},
					fail: (res) => {
						console.log('fail', res);
						if(res.code === -1 && res.data === "权限") {
							// 提示用户授予权限
							uni.showModal({
								title: '提示',
								content: '需要闹钟权限才能使用此功能，请在系统设置中授予权限',
								confirmText: '去设置',
								success: function (res) {
									if (res.confirm) {
										// 打开应用设置页面
										if(uni.getSystemInfoSync().platform === 'android') {
											plus.runtime.openURL('package:' + plus.runtime.appid);
										}
									}
								}
							});
						}
					},
					complete: () => {
						console.log('complete');
					},
				});
			},
			
			// 切换到下一个周期
			switchToNextCycle(alarm) {
				const updatedAlarm = switchToNextCycle(alarm);
				
				// 如果成功切换周期并且闹钟启用，重新设置系统闹钟
				if (updatedAlarm && updatedAlarm.enabled) {
					this.setSystemAlarm(updatedAlarm);
				}
			}
		}
	};
</script>

<style>
	.container {
		padding: 20rpx;
	}
	
	.header {
		padding: 20rpx 0;
		margin-bottom: 30rpx;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
	}
	
	.form-item {
		display: flex;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #EEEEEE;
	}
	
	.label {
		width: 180rpx;
		font-size: 30rpx;
		color: #333333;
	}
	
	.input {
		flex: 1;
		height: 80rpx;
		font-size: 30rpx;
	}
	
	.picker-value {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 30rpx;
	}
	
	.weekday-selector {
		flex: 1;
		display: flex;
		justify-content: space-between;
	}
	
	.weekday-item {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		background-color: #F5F5F5;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
	}
	
	.weekday-item.selected {
		background-color: #007AFF;
		color: #FFFFFF;
	}
	
	.switch-label {
		margin-left: 20rpx;
		font-size: 30rpx;
	}
	
	.btn-group {
		display: flex;
		justify-content: space-between;
		margin-top: 60rpx;
	}
	
	.btn {
		width: 45%;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		border-radius: 45rpx;
		font-size: 32rpx;
	}
	
	.cancel {
		background-color: #F5F5F5;
		color: #333333;
	}
	
	.save {
		background-color: #007AFF;
		color: #FFFFFF;
	}
	
	.custom-cycle-toggle {
		margin-top: 20rpx;
		background-color: #f0f0f0;
		border-radius: 10rpx;
		padding: 20rpx;
	}
	
	.custom-cycle-info {
		margin: 10rpx 0;
	}
	
	.custom-cycle-desc {
		font-size: 24rpx;
		color: #FF3B30;
		line-height: 1.4;
	}
	
	.custom-cycle {
		flex: 1;
	}
	
	.cycle-item {
		margin-bottom: 20rpx;
	}
	
	.cycle-label {
		display: block;
		font-size: 28rpx;
		color: #666666;
		margin-bottom: 10rpx;
	}
</style>